﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
public partial class customer : System.Web.UI.Page
{

    //Inject log4net
    private static readonly ILog logger = LogManager.GetLogger(typeof(customer).Name);

    private  const int PAGE_SIZE = 10;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Page.IsPostBack)
            {
                LoadToRepeater();
                lblMsg.Visible = false;
                btnFirst.Enabled = btnPrev.Enabled = false;
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            lblMsg.Visible = true;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }

    private void LoadToRepeater()
    {        
        Customer cust = new Customer();
        MonthCard month = new MonthCard();

        if (Page.IsPostBack) 
        {
            if (!String.IsNullOrEmpty(txtCode.Text.Trim()))//code
            {
                cust.CustomerCode = txtCode.Text.Trim();
            }
            if (!String.IsNullOrEmpty(txtName.Text.Trim()))//name
            {
                cust.CustomerName = txtName.Text.Trim();
            }
            if (!String.IsNullOrEmpty(txtPlat.Text.Trim()))//Plat
            {
                month.PlateNumber = txtPlat.Text.Trim();
               
            }
        }
        cust.MonthCard = month;


        IList<Customer> list = cust.GetByCustomerPaging(CurrentPage, PAGE_SIZE);
        rptCustomer.DataSource = list;
        rptCustomer.DataBind();
        if (list.Count == 0)
        {
            lblInform.Text = "Không có khách hàng nào";
            lblInform.Visible = true;
        }

        GetTotalPage(cust);
    }

    private void GetTotalPage(Customer cus)
    {
        int totalPage = 0;
        int records=cus.GetByCustomerPagingTotal();
       // totalPage = records / PAGE_SIZE;

        totalPage = records / PAGE_SIZE;
        //kiem tra co sang trang ko
        int div = records % PAGE_SIZE;
        if (div != 0)
        {
            totalPage ++;
        }

        btnFirst.Enabled = btnPrev.Enabled = btnNext.Enabled = btnLast.Enabled = (totalPage>1);
       

        //Set paging
        ltrPage.Text = String.Format("{0}/{1}", CurrentPage, totalPage);
        ViewState["TotalPage"] = totalPage;
    }


    /// <summary>
    /// Delete
    /// </summary>
    /// <param name="id"></param>
    private void Delete(Guid id)
    {
        try
        {
            Customer cus = new Customer();
            if (cus.CanDelete(id))
            {
                cus.Delete(id);
                LoadToRepeater();
            }
            else
            {
                lblMsg.Text = "Không thể xóa vì khách hàng này đang được sử dụng.";
                lblMsg.Visible = true;
            }
            
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// Delete
    /// </summary>
    /// <param name="id"></param>
    private void DeleteTicket(Guid id)
    {
        try
        {
            MonthCard month = new MonthCard();
            month.Delete(id);
            LoadToRepeater();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// When press icons
    /// </summary>
    /// <param name="strCommandName"></param>
    /// <param name="strArgument"></param>
    private void Action(string strCommandName, string strArgument)
    {
        switch (strCommandName.ToUpper())
        {
            //press delete button
            case "DELETECUSTOMER":
                Delete(new Guid(strArgument));
                break;
            //press delete button
            case "DELETETICKET":
                DeleteTicket(new Guid(strArgument));
                break;
            case "EDITCUSTOMER":
                //Response.Redirect(string.Format("CustomerAction.aspx?page=5&id={0}", strArgument));
                this.Context.Items["CommandName"] = strCommandName;
                this.Context.Items["id"] = strArgument;
                Server.Transfer("customerAction.aspx");
                break;
            case "SELL":
                this.Context.Items["CommandName"] = strCommandName;
                this.Context.Items["id"] = strArgument;
                Server.Transfer("monthTicketAction.aspx");
                //Response.Redirect(string.Format("MonthTicketAction.aspx?page=5&act=sell&id={0}", strArgument));
                break;
            case "EDITTICKET":
                this.Context.Items["CommandName"] = strCommandName;
                this.Context.Items["id"] = strArgument;
                Server.Transfer("monthTicketAction.aspx");
                //Response.Redirect(string.Format("MonthTicketAction.aspx?page=5&act=edit&id={0}", strArgument));
                break;
            case "EXTEND":
                this.Context.Items["CommandName"] = strCommandName;
                this.Context.Items["id"] = strArgument;
                Server.Transfer("monthTicketAction.aspx");
                //Response.Redirect(string.Format("MonthTicketAction.aspx?page=5&act=extend&id={0}", strArgument));

                break;
            default:
                break;
        }
    }


   
    protected void btnSearch_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            LoadToRepeater();
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            lblMsg.Visible = true;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }



    protected void rptCustomer_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        try
        {
            //get command
            string strCommandName = e.CommandName.Trim();
            string strArgument = e.CommandArgument.ToString().Trim();

            //hdnId.Value = strArgument;
            Action(strCommandName, strArgument);
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            lblMsg.Visible = true;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }
    protected void rptCustomer_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            Customer customer = (Customer)e.Item.DataItem; ;

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                //find control
                ImageButton btnDeleteTicket = (ImageButton)e.Item.FindControl("btnDeleteTicket");
                ImageButton btnEditTicket = (ImageButton)e.Item.FindControl("btnEditTicket");
                ImageButton btnExtend = (ImageButton)e.Item.FindControl("btnExtend");                

                if (customer.MonthCard != null && !String.IsNullOrEmpty(customer.MonthCard.PlateNumber))
                {
                    btnDeleteTicket.ImageUrl = @"~/images/delete.gif";
                    btnDeleteTicket.ToolTip = "Xóa vé tháng";

                    btnEditTicket.ImageUrl = @"~/images/edit.png";
                    btnEditTicket.ToolTip = "Sửa vé tháng";

                    btnExtend.ImageUrl = @"~/images/extendIcons.png";
                    btnExtend.ToolTip = "Gia hạn vé tháng";
                }
                else
                {
                    btnDeleteTicket.Visible = false;
                    btnEditTicket.Visible = false;
                    btnExtend.Visible = false;
                }

                //ImageButton btnDeleteCustomer = (ImageButton)e.Item.FindControl("btnDeleteCustomer");
                //btnDeleteCustomer.Visible = !btnExtend.Visible;
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            lblMsg.Visible = true;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }





    #region Paging
    protected void btnLast_Click(object sender, ImageClickEventArgs e)
    {
        CurrentPage = int.Parse(ViewState["TotalPage"].ToString());
        LoadToRepeater();
        btnLast.Enabled = btnNext.Enabled = false;
        btnFirst.Enabled = btnPrev.Enabled = true;
    }
    protected void btnFirst_Click(object sender, ImageClickEventArgs e)
    {
        CurrentPage = 1;
        LoadToRepeater();
        btnLast.Enabled = btnNext.Enabled = true;
        btnFirst.Enabled = btnPrev.Enabled = false;
    }
    protected void btnPrev_Click(object sender, ImageClickEventArgs e)
    {
        CurrentPage--;
        LoadToRepeater();
        if (int.Parse(ViewState["TotalPage"].ToString()) == 1)
        {
            btnLast.Enabled = btnNext.Enabled = true;
            btnFirst.Enabled = btnPrev.Enabled = false;
        }
    }
    protected void btnNext_Click(object sender, ImageClickEventArgs e)
    {
        CurrentPage++;
        LoadToRepeater();
        if (CurrentPage == int.Parse(ViewState["TotalPage"].ToString()))
        {
            btnLast.Enabled = btnNext.Enabled = false;
            btnFirst.Enabled = btnPrev.Enabled = true;
        }

    }

    private int CurrentPage
    {
        get
        {
            object objPage = ViewState["_CurrentPage"];
            int _CurrentPage = 1;
            if (objPage == null)
            {
                _CurrentPage = 1;
            }
            else
            {
                _CurrentPage = (int)objPage;
            }
            return _CurrentPage;
        }
        set { ViewState["_CurrentPage"] = value; }
    } 
    #endregion

}